import { VCourseSlotScens ,CourseSlotReq ,CourseSlotScensReq} from '../../types/vCourseSlotScens'
import { VCourseSlotScensDao } from '../dao/vCourseSlotScensDao'
import { CourseDao } from '../dao/courseDao'
import { CourseSlotDao } from '../dao/courseSlotDao'
import { TrainerCourseDao } from '../dao/trainerCourseDao'
import { TrainerCourse } from '../../types/trainerCourse'
import { Interactive } from '../../utils/Interactive'
import { SiteConfigDao } from '../dao/siteConfigDao'
import {TrainRecordDao} from '../dao/trainRecordDao'
import {CourseTimeService} from './courseTimeService'
export class VCourseSlotScensService {
  /**
   * 获取视图详情
   */
  static async getById(id: number): Promise<VCourseSlotScens> {
    return VCourseSlotScensDao.getById(id)
  }

  /**
   * 获取视图列表
   */
  static async list(params: CourseSlotReq) {
    return VCourseSlotScensDao.list(params)
  }

  /**
   * 添加排课课程
   */
  static async add(params: CourseSlotScensReq) {
    //console.log('params',params)
    if(!params.train_doctor_id){
      throw new Error('请选择训练康复师')
    }
    if(!params.course_date){
      throw new Error('请选择课程日期')
    }
    if(!params.course_time_id){
      throw new Error('请选择课程场次')
    }
    // if(!params.ar_duration){
    //   throw new Error('请选择课程时长')
    // }
    if(!params.sound_bars){
      throw new Error('请选择训练阶梯')
    }
    if(!params.secens_id){
      throw new Error('请选择课程场景')
    }
    //如果没有训练人员，抛出异常
    if(!params.trainers){
      throw new Error('请选择参训人员')
    }
  /**{
      course_time: params.course_time,
      train_doctor: params.train_doctor_id,
      course_date: params.course_time,
    } as Course */  
    //创建课程
    const course = {
      course_time: params.course_time_id,
      train_doctor: params.train_doctor_id,
      course_date: params.course_date,
      total_time: 0
    }
  
    //根据course_time查询
    const courseTime = await CourseTimeService.findById(params.course_time_id)
    //已知course_time查询course_time(hh:mm)表的start_time和end_time(hh:mm)
    if(courseTime){
      //计算courseTime.start_time到  courseTime.start_time相隔几秒    
        const startTime =  new Date(params.course_date+'T'+courseTime.start_time+':00')
        const endTime =  new Date(params.course_date+'T'+courseTime.end_time+':00')
        const total_time = (endTime.getTime() - startTime.getTime()) / 1000
        course.total_time = total_time
    }
    //console.log('course',course)
    //创建课程
    const courseId = await CourseDao.create(course)

    /**
     *      id?: number
            course_id?: number
            course_time_id?: string
            ar_duration?: number
            sound_bars?: number
            secens_id?: number
     */

    const courseSlot =  {
      course_id: courseId,
      course_time_id: params.course_time_id,
      ar_duration: params.ar_duration,
      sound_bars: params.sound_bars,
      secens_id: params.secens_id
    }
    //创建课程
    const courseSlotId = await CourseSlotDao.create(courseSlot)
    //console.log('courseSlotId',params.trainers)
    if(params.trainers){
      for(let trainer_id of params.trainers){
        //创建训练人员课程
        const trainerCourse = {
          course_id: courseId,
          trainer_id: trainer_id,
          slot_id: courseSlotId
        }
        //创建训练人员课程
        await TrainerCourseDao.create(trainerCourse)
      }
    }
    
    return courseSlotId;
  }

  /**
   * 编辑排课课程
   * @param params 
   * @returns 
   */
  static async edit(params: CourseSlotScensReq) {
    //console.log('params',params)
    if(!params.id){
      throw new Error('请选择排课课程')
    }
    if(!params.train_doctor_id){
      throw new Error('请选择训练康复师')
    }
    if(!params.course_date){
      throw new Error('请选择课程日期')
    }
    if(!params.course_time_id){
      throw new Error('请选择课程时间')
    }
   // if(!params.ar_duration){
   //   throw new Error('请选择课程时长')
   // }
    if(!params.sound_bars){
      throw new Error('请选择训练阶梯')
    }
    if(!params.secens_id){
      throw new Error('请选择课程场景')
    }
    //如果没有训练人员，抛出异常
    if(!params.trainers){
      throw new Error('请选择参训人员')
    }

    //根据id查询排课课程
    const courseSlot = await CourseSlotDao.getById(params.id)
    if(!courseSlot){
      throw new Error('排课课程不存在')
    }
    //console.log("courseSlot",courseSlot)
    courseSlot.sound_bars = params.sound_bars
    courseSlot.ar_duration = params.ar_duration
    courseSlot.secens_id = params.secens_id
    //更新排课课程
    await CourseSlotDao.update(params.id, courseSlot)

    //更新课程医生
    //更新课程医生
    const course = {
      train_doctor: params.train_doctor_id,
      total_time: 0
    }
    //根据course_time查询
    const courseTime = await CourseTimeService.findById(params.course_time_id)
    //已知course_time查询course_time(hh:mm)表的start_time和end_time(hh:mm)
    if(courseTime){
      //计算courseTime.start_time到  courseTime.start_time相隔几秒    
        const startTime =  new Date(params.course_date+'T'+courseTime.start_time+':00')
        const endTime =  new Date(params.course_date+'T'+courseTime.end_time+':00')
        const total_time = (endTime.getTime() - startTime.getTime()) / 1000
        course.total_time = total_time
    }
    //console.log('course',course)
    await CourseDao.update(courseSlot.course_id, course)

    //根据id查询训练人员课程
    const trainerCourse = {
      slot_id: params.id
    } as TrainerCourse
    const trainerCourses = await TrainerCourseDao.list(trainerCourse)
    //console.log("trainerCourses",trainerCourses)
    //删除训练人员课程
    if(trainerCourses){
      for(let trainerCourse of trainerCourses){
        await TrainerCourseDao.delete(trainerCourse.id)
      }
    }
   // console.log("params.trainer",params.trainers)
    if(params.trainers){
      for(let trainer_id of params.trainers){
        //创建训练人员课程
        const trainerCourse = {
          course_id: courseSlot.course_id,
          trainer_id: trainer_id,
          slot_id: courseSlot.id
        }
        //创建训练人员课程
        await TrainerCourseDao.create(trainerCourse)
      }
    }
    //删除训练记录，重新训练
    return trainerCourse.id
  }
  
  //实现删除方法
  static async del(id: number) {
    //根据id查询排课课程
    const courseSlot = await CourseSlotDao.getById(id)
    if(!courseSlot){
      throw new Error('排课课程不存在')
    }
    //删除Course
    await CourseDao.delete(courseSlot.course_id)
    //根据id查询训练人员课程
    const trainerCourse = {
      slot_id: id
    } as TrainerCourse
    const trainerCourses = await TrainerCourseDao.list(trainerCourse)
    //删除训练人员课程
    if(trainerCourses){
      for(let trainerCourse of trainerCourses){
        await TrainerCourseDao.delete(trainerCourse.id)
      }
    }
    //删除排课课程
    await CourseSlotDao.delete(id)
    //删除训练记录
    await TrainRecordDao.deleteBySoltId(courseSlot.id)
  }


  /**
   * 
   * @param id 课程id
   * @returns 课程进度
   */
  static async getProcess(id: number): Promise<number | null> {
    const vsolt = await this.getById(id)
    const course = await CourseDao.getById(vsolt.course_id)
    if(!course){
      return 0
    }
    if(!course.start_time){
      return 0
    }
    //默认未训练
    if(!course.total_time){
      return 0
    }
    //已知start_time和total_time计算process
    if(course.start_time && course.total_time>0){
      const startTime = new Date(course.start_time)
      const seconds = await this.getSecondsDifference(startTime,new Date())
      let process = parseFloat((seconds*100 /course.total_time).toFixed(2))
      if(process>=100){
        process = 100
      }
      //更新课程进度
      const courseTmp = {
        id: id,
        process: process
      }
      await CourseDao.update(id, courseTmp)
      return process
    }
    return 0
  }

  static async start(id: number) {
    //console.log('id',id)
    const siteConfig = await SiteConfigDao.getById(1)
    if(!siteConfig){
      throw new Error('站点配置不存在')
    }
    const courseSlot = await VCourseSlotScensDao.getById(id)
    if(!courseSlot){
      throw new Error('排课课程不存在')
    }
    try{
      //根据
      const interactive = new Interactive()
      //console.log('siteConfig',siteConfig)
     // console.log('courseSlot',courseSlot)
     // console.log('courseSlot',courseSlot.secens_id)
      const result = await interactive.start(courseSlot.secens_id, siteConfig)
     // console.log('result',result)
      if(result){
        //将trainer 写入 trainRexord中
        const trainerCourses = await TrainerCourseDao.list({ slot_id: id,course_id: courseSlot.course_id } as TrainerCourse)
       // console.log("trainerCourses",trainerCourses)
        if(trainerCourses){
          const record = {
            slot_id: courseSlot.id,
            course_id: courseSlot.course_id
          }
          const recordList = await TrainRecordDao.list(record)
          // console.log("recordList",recordList)
          if(recordList && recordList.length>0){
            for(const item of recordList){
              await TrainRecordDao.delete(item.id)
            }
          }
          for(let trainerCourse of trainerCourses){
            const trainRecord = {
              trainer_id: trainerCourse.trainer_id,
              course_id: trainerCourse.course_id,
              slot_id: trainerCourse.slot_id,
              scense_id: courseSlot.secens_id,
            }
            await TrainRecordDao.add(trainRecord)
          }
          //如果成功，修改course表中的course_status 为2  //训练中
          //更新课程医生
          const course = {
            id: courseSlot.course_id,
            //年-月-日 时:分:秒
            // 使用北京时间 (UTC+8)
            start_time: new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString().split('.')[0],
            train_status: 2
          }
         // console.log('course',course)
          await CourseDao.update(courseSlot.course_id, course)
        }
      }
    } catch (e) {
      console.error('播放失败', e);
      throw new Error('播放失败');
    }
  }

  //停止方法
  static async stop(id: number) {
    const siteConfig = await SiteConfigDao.getById(1)
    if(!siteConfig){
      throw new Error('站点配置不存在')
    }
    const courseSlot = await VCourseSlotScensDao.getById(id)
    if(!courseSlot){
      throw new Error('排课课程不存在')
    }
    const interactive = new Interactive()
    const result = await interactive.stop(siteConfig)
    if(result){
      //如果成功，修改course表中的course_status 为1   //已完成
       //更新课程医生
      const course = {
        id: courseSlot.course_id,
        train_status: 1,
        process: 100,
        end_time: new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString().split('.')[0],
      }
      await CourseDao.update(courseSlot.course_id, course)
    }
  }

  static async getSecondsDifference(date1: Date, date2: Date): Promise<number>  {
    // 获取两个日期的时间戳（毫秒）
    const time1 = date1.getTime();
    const time2 = date2.getTime();

    // 计算差值（毫秒），再转换为秒
    // 返回 date2 - date1 的差值（以秒为单位）
    const differenceInSeconds = (time2 - time1) / 1000;

    // 取整数部分（向零取整）
    return Math.trunc(differenceInSeconds);
  }
}
